#!/usr/bin/python2.6

import threading
import time
import InitConfig as config
import logging
import log_file
import urllib2
import json
import os
import xmlrpclib
import rpcServer

a = config.Config()
ip = a.getWebIP()
port = a.getWebPort()
cobbler_ip = a.getCobblerIp()
webProject = a.getWebProJectName()
log_path = a.getLogPath()
action = a.getWebAction()
ks_path = a.getKsPath()
ks_file = a.getKsTemplateFile()
sync_ks_intval = a.getSyncKsInterval()
syncKicstartsAction = a.getSyncKicstartsAction()


logging.basicConfig(filename=log_path, level=logging.DEBUG)

class myThread(threading.Thread):
    def __init__(self, num, interval):
        threading.Thread.__init__(self)
        self.thread_num = num
        self.interval = interval

    def run(self):
        while True:
            self.checedKs()
            time.sleep(self.interval)

    def checedKs(self):
        """
        register to web project
        :return:
        """
        synToJavaUrl = "http://%s:%s/%s/%s?account=guopengfei&receiver=0001" % (ip, port, webProject, syncKicstartsAction)
        values = {"type": "checkKs"}
        jdata = json.dumps(values)
        sendType = True
        try:
            req = urllib2.Request(url=synToJavaUrl, headers={'Content-type': 'text/json'})
            req.add_data(jdata)
            rep = urllib2.urlopen(req)
            kistarts = rep.read()
            jdata = json.loads(kistarts)
            self.__syncLocalKistart(jdata)
            sendType = True
        except:
            sendType = False
        finally:
            log_file.writeTextLog("syncKs", content="get Kicstart file status is %s \n" % (sendType))

    def __syncLocalKistart(self, kistarts):
        """
        parse all ks data from web project.
        And modify profile with ks file and iso tree
        :param kistarts: all ks data of json type
        :return:
        """
        # jdata = kistarts
        for f in range(len(kistarts)):
            evKis = kistarts[f]
            ksName = evKis["ksName"]
            osName = evKis["osName"]
            langue = "%s" % (evKis["langue"])
            timezone = "timezone %s" % (evKis["timezone"])
            roopw = evKis["roopw"]
            partitions = evKis["partitions"]
            par = ""
            if(partitions.strip() is not ''):
                pars = partitions.split(';')
                for h in range(len(pars)):
                    evpar = pars[h].split(',')
                    par +='part %s --fstype="%s" --size="%s"\n' % (evpar[0], evpar[1], evpar[2])

            #  由数组变成字符串
            # par = ""
            # for h in range(len(partitions)):
            #     partition = partitions[h]
            #     part = partition["part"]
            #     fstype = partition["fstype"]
            #     size = partition["size"]
            #     par += 'part %s --fstype="%s" --size="%s"\n' % (part, fstype, size)

            packages = evKis["packages"]
            package = ""
            # for i in range(len(packages)):
            #     package += packages[i]

            if(packages.strip() is not ''):
                evpac = packages.split(',')
                for i in range(len(evpac)):
                    package +=evpac[i]+'\n'

            post = evKis["post"]+'\n'
            server ,token = rpcServer.getCobblerService()
            disTro = server.get_distro(osName,token)

            if disTro =="~":
                # distro  file is not exist ,and not exec "cobbler import " shell ,so we can't sync ks file and modify profile file message
                continue
            # try:
            #     server.remove_profile(profileName,token)   # delete this profile first!
            # except:
            #     log_file.writeTextLog("synKs","profile for '%s' is not exist!"%(profileName))
            # if not a :
            #     #remove fail ,continue
            #     continue

            ##check profile is exist?
            targetDir, flag = self.__newKs(ksName, osName, langue, timezone, roopw, par, package, post)
            #if profile is eixst with this "ksName" we should not create or modify it !
            try:
                distro_id = server.get_profile_handle(ksName,token)
                #profile exist , pass...
            except:
                #not exist ,create new profile ...
                distro_id = server.new_profile(token)
                a = server.modify_profile(distro_id, 'kickstart', targetDir, token)
                b = server.modify_profile(distro_id, 'name', ksName, token)
                c = server.modify_profile(distro_id, 'distro', osName, token)
                d = server.save_profile(distro_id, token)
            # server.sync(token)


    def __newKs(self, ksName, osName, langue, timezone, roopw, par, package, post):
        """
        make a new ks file for all parameter frome template file "template.ks"
        :param ksName:  ks name
        :param osName: iso full name,example:centos-6.5-86_64.iso
        :param langue: langue
        :param timezone: timezone
        :param roopw: root password
        :param par: Partition information
        :param package: The package to be installed
        :param post: execution of the scrip after the installed.
        :return:
        """
        # profileName = osName[:osName.rfind(".")]
        sourceFile = ks_path + ks_file
        targetDir = ks_path + "%s.ks" % (ksName)
        if os.path.exists(targetDir):
            os.remove(targetDir)

        file1 = open(sourceFile, "r")
        targetDir1 = open(targetDir, "a+")

        for c in file1:
            if "@@@langue" in c:
                line = c.replace("@@@langue", langue)
            elif "@@@profileUrl" in c:
                line = c.replace("@@@profileUrl","http://%s/cobbler/ks_mirror/%s"%(cobbler_ip, osName))
            elif "@@@timezone" in c:
                line = c.replace("@@@timezone", timezone)
            elif "@@@rootpw" in c:
                line = c.replace("@@@rootpw", roopw)
            elif "@@@part" in c:
                line = c.replace("@@@part", par)
            elif "@@@package" in c:
                line = c.replace("@@@package", package)
            elif "@@@post" in c:
                line = c.replace("@@@post", post)
            else:
                line = c
            targetDir1.writelines(line)

        targetDir1.close()
        return targetDir  ,True


if __name__ == "__main__":
    thread1 = myThread(1, int(sync_ks_intval))
    # thread1.setDaemon(True)
    thread1.start()
